package com.melihelibol.stratosphere.net {
	
	/*
	Copyright (c) <2009> <copyright H. Melih Elibol>
	
	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:
	
	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.
	
	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
	*/
	
	import com.melihelibol.stratosphere.Stratosphere;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.NetStatusEvent;
	import flash.net.*;
	
	public class PeerConnection extends EventDispatcher {
		
		public static const NETWORK_NAME:String = "com.melihelibol.stratosphere";
		
		public static const INIT_CONNECTION_COMPLETE:String = "initConnectionComplete";
		public static const INIT_SEND_STREAM_COMPLETE:String = "initSendStreamComplete";
		public static const INIT_RECIEVE_STREAM_COMPLETE:String = "initRecieveStreamComplete";
		
		public static const INIT_CONNECTION:String = "initConnection";
		public static const INIT_SEND_STREAM:String = "initSendStream";
		public static const INIT_RECIEVE_STREAM:String = "initRecieveStream";
		public static const CONNECTED:String = "connected";
		
		private var stratosphere:Stratosphere;
		
		private var nc:NetConnection;
		
		private var sendStream:NetStream;
		private var sendStreamClient:Object;
		
		private var recieveStream:NetStream;
		private var recieveStreamClient:Object;
		
		public var phase:String;
		
		public var localPeerID:String;
		public var remotePeerID:String;
		public var remoteClientID:String;
		
		public var closed:Boolean = false;
		
		public function PeerConnection(stratosphere:Stratosphere) {
			this.stratosphere = stratosphere;
		}
		
		public function open():void {
			phase = INIT_CONNECTION;
			nc = new NetConnection();
			nc.addEventListener(NetStatusEvent.NET_STATUS, connectionStatus);
			nc.connect(Stratosphere.SERVER_ADDRESS+stratosphere.developerKey);
		}
		
		public function close():void {
			closed = true;
			if(sendStream){
				sendStream.removeEventListener(NetStatusEvent.NET_STATUS, sendStatus);
				sendStream.close();
				sendStream = null;
			}
			if(recieveStream){
				recieveStream.removeEventListener(NetStatusEvent.NET_STATUS, recieveStatus);
				recieveStream.close();
				recieveStream = null;
			}
			if(nc){
				nc.removeEventListener(NetStatusEvent.NET_STATUS, connectionStatus);
				nc.close();
				nc = null;
			}
		}
		
		//is it possible to get two different requests to the same connection?
		public function receiveConnection(remotePeerID:String):Boolean {
			if(phase == PeerConnection.INIT_SEND_STREAM_COMPLETE){
				this.remotePeerID = remotePeerID;
				initRecieveStream();
			}
			return true;
		}
		
		private function initSendStream():void {
			phase = INIT_SEND_STREAM;
			sendStream = new NetStream(nc, NetStream.DIRECT_CONNECTIONS);
			sendStream.addEventListener(NetStatusEvent.NET_STATUS, sendStatus);
			sendStream.publish(NETWORK_NAME);
			sendStreamClient = new Object();
			sendStreamClient.test = "hello";
			sendStreamClient.onPeerConnect = sendStreamOnPeerConnect;
			sendStream.client = sendStreamClient;
		}
		
		private function initRecieveStream():void {
			if(recieveStream) throw new Error("receive stream already open!");
			phase = INIT_RECIEVE_STREAM;
			recieveStream = new NetStream(nc, remotePeerID);
			recieveStreamClient = new Object();
			recieveStream.client = recieveStreamClient;
			recieveStream.addEventListener(NetStatusEvent.NET_STATUS, recieveStatus);
			recieveStream.play(NETWORK_NAME);
		}
		
		/**
		 * Stream Handlers
		 */
		
		private function connectionStatus(e:NetStatusEvent):void {
			trace("connectionStatus", e.info.code);
			if(phase == INIT_CONNECTION){
				localPeerID = nc.nearID;
				dispatchEvent(new Event(INIT_CONNECTION_COMPLETE));
				phase = INIT_CONNECTION_COMPLETE;
				initSendStream();
			}
		}
		
		private function sendStatus(e:NetStatusEvent):void {
			trace("sendStatus", e.info.code);
			if(INIT_SEND_STREAM){
				phase = INIT_SEND_STREAM_COMPLETE;
				dispatchEvent(new Event(INIT_SEND_STREAM_COMPLETE));
				if(this.remotePeerID && !recieveStream){
					initRecieveStream();
				}
			}
		}
		
		private function recieveStatus(e:NetStatusEvent):void {
			trace("recieveStatus", e.info.code);
			if(INIT_RECIEVE_STREAM){
				phase = INIT_RECIEVE_STREAM_COMPLETE;
				dispatchEvent(new Event(INIT_RECIEVE_STREAM_COMPLETE));
				phase = CONNECTED;
			}
		}
		
		private function sendStreamOnPeerConnect(callerNS:NetStream):Boolean {
			return receiveConnection(callerNS.farID);
		}
		
		/**
		 * Handler API
		 */
		
		public function addMessageHandler(name:String, handler:Function):void {
			recieveStreamClient[name] = handler;
		}
		
		public function removeMessageHandler(name:String):void {
			delete recieveStreamClient[name];
		}
		
		public function send(message:String, ...args):void {
			sendStream.send(message, args);
		}
		
	}
	
}